import pandas as pd

df=pd.read_csv('bayes_lihang.txt')
#P存放概率值的字典
P={}

def tokey(x,x_v,y):
    return str(x)+'='+str(x_v)+str('|Y=')+str(y)

#平滑系数
lam=1
#Y中存储标签类别
Y=df['Y'].value_counts().index.tolist()
print(Y)
#xs存储特征名 x1 x2
Xs=df.columns.tolist()[:-1]
print(df)
for y in Y:
    # Y:1,-1
    #df2中为y=1
    df2=df[df['Y']==y]
    p=(df2.shape[0]+lam)/(df.shape[0]+lam*len(Y))
    P[y]=p
    for x in Xs:
        # xs:x1,x2
        x_vs=df[x].value_counts().index.tolist()
        for i in x_vs:
            # x_vs:[1,2,3],[s,m,l]
            df3=df2[df2[x]==i]
            p=(df3.shape[0]+lam)/(df2.shape[0]+lam*len(x_vs))
            k=tokey(x,i,y)
            P[k]=p
print(P)

X=[2,'S']
res=[]
for y in Y:
    p=P[y]
    for  i in range(len(X)):
        k=tokey(Xs[i],X[i],y)
        p=p*P[k]
    res.append(p)
print(res)

import numpy as np
ix=np.argmax(res)
print('Y的类别Y[ix]')
print(Y[ix])